function TimeSync() {
    this.baseDate = null;
    this.startDate = null;
    this.count = 0;
    this.updateBaseDateInterval = null;
    this.window = null;
    this.screenWidth = device.width;
    this.screenHeight = device.height;
    this.updateInterval = null;  // 用于保存时钟更新的 interval
}

TimeSync.prototype.init = function() {
    this.createFloatingWindow();
};

// 获取本地时间，并同步网络时间
TimeSync.prototype.getLocalDate = function() {
    if (!this.baseDate && this.count <= 3) {
        let timestamp = this.getAccurateTimestamp();
        this.baseDate = new Date(timestamp);
        this.startDate = new Date();
        this.count++;
    }

    if (!this.updateBaseDateInterval && this.count <= 3) {
        const delay = 10;
        this.updateBaseDateInterval = setInterval(() => {
            let nowTimestamp = new Date().getTime();
            let diff = Math.abs(nowTimestamp - this.startDate.getTime());
            this.startDate = new Date(nowTimestamp);
            this.baseDate = new Date(this.baseDate.getTime() + diff);
        }, delay);
    }

    return this.baseDate;
};

// 获取网络时间戳并修正本地时间的延迟
TimeSync.prototype.getAccurateTimestamp = function() {
    const startLocalTime = new Date().getTime();
    let timestamp = this.getTaobaoTimestamp();
    const endLocalTime = new Date().getTime();
    const networkDelay = Math.floor((endLocalTime - startLocalTime) / 2);
    return timestamp + networkDelay;
};

// 获取时间戳
TimeSync.prototype.getTime = function() {
    try {
        var response = http.get("https://db.yearnstudio.cn/time");
        if (response.statusCode !== 200) {
            throw new Error("请求失败，状态码: " + response.statusCode);
        }
        const timestamp = parseInt(response.body.string());
        return timestamp;
    } catch (e) {
        console.error("网络时间获取失败，采用本地时间:", e.message);
        return new Date().getTime();
    }
};

// 淘宝时间戳API
TimeSync.prototype.getTaobaoTimestamp = function() {
    try {
        var response = http.get("http://acs.m.taobao.com/gw/mtop.common.getTimestamp/");
        const data = response.body.json();
        return parseInt(data.data.t); 
    } catch (e) {
        console.error("获取淘宝时间戳失败:", e.message);
        return new Date().getTime();
    }
};

// 创建悬浮窗
TimeSync.prototype.createFloatingWindow = function() {
    this.window = floaty.window(
        <vertical id="frame" bg="#000000" alpha="0.8" padding="8dp">
            <horizontal>
                <text textSize="16sp" textColor="#ffffff" text="北京时间:" />
                <text id="timeText" textSize="16sp" textColor="#ffffff"/>
            </horizontal>
            <horizontal>
                <text textSize="16sp" textColor="#ffffff" text="本机时间:" />
                <text id="timeText2" textSize="16sp" textColor="#ffffff" />
            </horizontal>
        </vertical>
    );

    // 延迟 100 毫秒设置位置
    setTimeout(() => {
        this.window.setPosition(this.screenWidth - this.window.getWidth(), 0);
    }, 100);
};

// 启动时钟更新
TimeSync.prototype.startClock = function() {
    ui.run(() => {
        this.window.timeText.setText("网络校时中...");
    });

    this.updateInterval = setInterval(() => {
        const currentTime = this.getLocalDate();
        const timeString = this.formatTime(currentTime);
        ui.run(() => {
            this.window.timeText.setText(timeString);
            this.window.timeText2.setText(this.formatTime(new Date()));
        });
    }, 10);
};

// 停止时钟更新和悬浮窗
TimeSync.prototype.stop = function() {
    try {
        // 停止更新的定时器
        if (this.updateInterval) {
            clearInterval(this.updateInterval);
            this.updateInterval = null;
        }
        
        // 停止基准时间更新的定时器
        if (this.updateBaseDateInterval) {
            clearInterval(this.updateBaseDateInterval);
            this.updateBaseDateInterval = null;
        }

        // 隐藏悬浮窗
        if (this.window) {
            this.window.setAlpha(0);  // 隐藏悬浮窗
        }
    } catch (e) {
        console.error("停止过程出现异常:", e.message);
    }
};

// 启动时钟更新和悬浮窗
TimeSync.prototype.start = function() {
    if (this.updateInterval) return;  // 如果已经在运行，则不重复启动
    this.init();  // 初始化并启动
    this.startClock();  // 启动时钟
};

// 时间格式化函数
TimeSync.prototype.formatTime = function(date) {
    return [
        this.padZero(date.getHours()),
        this.padZero(date.getMinutes()),
        this.padZero(date.getSeconds())
    ].join(":") + "." + this.padMilliseconds(date.getMilliseconds());
};

// 两位补零函数
TimeSync.prototype.padZero = function(num) {
    return num < 10 ? "0" + num : num;
};

// 三位补零函数
TimeSync.prototype.padMilliseconds = function(ms) {
    return ms < 10 ? "00" + ms : (ms < 100 ? "0" + ms : ms);
};

// 初始化和启动
let timeSync = new TimeSync();
timeSync.start();  // 启动时钟和悬浮窗

var stop = false

setInterval(()=>{
    if(stop){
        // 如果需要重新启动
        timeSync.start();
    }else{
        // 停止时钟和悬浮窗
        timeSync.stop();
    }
    stop = !stop;
},10000)

setInterval(()=>{
    console.log("heart")
},10000)
